﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Microsoft.SharePoint;

namespace SPRepository
{
    public class MultiLookupFieldType : SimpleFieldType<IEnumerable<LookupFieldDto>>
    {
        public MultiLookupFieldType(Guid id) : base(id)
        {
        }

        public override IEnumerable<LookupFieldDto> GetValue(SPListItem item)
        {
            var fieldValueCollection = GetFieldValue<SPFieldLookupValueCollection>(item);
            List<LookupFieldDto> dtoList =
                fieldValueCollection.Select(
                    lookupValue => new LookupFieldDto(lookupValue.LookupId, lookupValue.LookupValue))
                                    .ToList();
            return dtoList;
        }

        public override void SetValue(SPListItem item, IEnumerable<LookupFieldDto> values)
        {
            var fieldValueCollection = new SPFieldLookupValueCollection();
            if (values != null)
            {
                foreach (LookupFieldDto value in values)
                {
                    var fieldValue = new SPFieldLookupValue(value.LookupId.ToString(CultureInfo.InvariantCulture));
                    fieldValueCollection.Add(fieldValue);
                }
            }
            item[FieldId] = fieldValueCollection;
        }
    }
}